package br.ufrj.ppgi.jemf_advanced_example;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import br.ufrj.ppgi.jemf_advanced_example.emergency.*;
import br.ufrj.ppgi.jemf_advanced_example.mission.*;
import br.ufrj.ppgi.jemf_advanced_example.affected_organization.*;
import br.ufrj.ppgi.jemf_advanced_example.commander.*;
import br.ufrj.ppgi.jemf_advanced_example.contact.*;
import br.ufrj.ppgi.jemf_advanced_example.equipment.*;
import br.ufrj.ppgi.jemf_advanced_example.health_care_unit.*;
import br.ufrj.ppgi.jemf_advanced_example.location.*;
import br.ufrj.ppgi.jemf_advanced_example.medical.*;
import br.ufrj.ppgi.jemf_advanced_example.plan.*;
import br.ufrj.ppgi.jemf_advanced_example.responder.*;
import br.ufrj.ppgi.jemf_advanced_example.task.*;
import br.ufrj.ppgi.jemf_advanced_example.team.*;
import br.ufrj.ppgi.jemf_advanced_example.text_message.*;
import br.ufrj.ppgi.jemf_advanced_example.victim.*;
import br.ufrj.ppgi.jemf_advanced_example.volunteer.*;
import br.ufrj.ppgi.jemf_advanced_example.witness.*;

public class MainActivity extends Activity {

	// Main Activity ListView.
	private ListView mainListView;
	// Slide menu items.
	private String[] navMenuTitles;
	// Slide menu icons.
	private TypedArray navMenuIcons;
	// Menu item list.
	private ArrayList<NavDrawerItem> navDrawerItems;
	// Menu adapter.
	private NavDrawerListAdapter adapter;



	// Clicking TWICE the back button to exit activity.
    private static final long delay = 2000L;
    private boolean mRecentlyBackPressed = false;
    private Handler mExitHandler = new Handler();
    private Runnable mExitRunnable = new Runnable() {
        @Override
        public void run() {
            mRecentlyBackPressed=false;   
        }
    };



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);



		// Load slide menu items.
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
		// Nav drawer icons from resources.
		navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
		// Menu list view.
		mainListView = (ListView) findViewById(R.id.list_slidermenu);

		// Adding Nav drawer items to array.
		navDrawerItems = new ArrayList<NavDrawerItem>();
		for(int i = 0; i < navMenuTitles.length ; i++){
			navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));
		}	

		// Recycle the typed array.
		navMenuIcons.recycle();
		// Setting the menu listener. 
		mainListView.setOnItemClickListener(new SlideMenuClickListener());
		// Setting the Nav drawer list adapter.
		adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
		mainListView.setAdapter(adapter);
	}

	/*
	 * Menu item click listener.
	 */
	private class SlideMenuClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// Display view for selected Nav drawer item.
			displayView(position);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar actions click.
		switch (item.getItemId()) {
			case R.id.action_info:
				AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
				// Setting Dialog Title.
				alertDialog.setTitle("Info About");
				// Setting Dialog Message.
				alertDialog.setMessage("Java Emergency Management Framework (JEMF), \n" +
										"Advanced Example. \n\n" +
										"Created by Marcus Machado, \n" +
										"Federal University of Rio de Janeiro (UFRJ): \n" +
										"marcus.machado@ppgi.ufrj.br \n\n" +
										"This program is free software under " +
										"General Public License version 3 or later.");
				// Setting Icon to Dialog.
				alertDialog.setIcon(R.drawable.ic_launcher);
				// Setting OK Button.
				alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// After dialog closed.
					}
				});
		        // Showing Alert Message.
		        alertDialog.show();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * Displaying fragment view for selected Nav drawer list item.
	 */
	private void displayView(int position) {
		// Update the main content by replacing fragments.
		Class<?> classe = null;
		switch (position) {
		case 0:
			// Emergency activity.
			classe = EmergencyListActivity.class;
			break;
		case 1:
			// Mission activity.
			classe = MissionListActivity.class;
			break;
		case 2:
			// Task activity.
			classe = TaskListActivity.class;
			break;
		case 3:
			// Affected Organization activity.
			classe = AffectedOrganizationListActivity.class;
			break;
		case 4:
			// Health Care Unit activity.
			classe = HealthCareUnitListActivity.class;
			break;
		case 5:
			// Equipment activity.
			classe = EquipmentListActivity.class;
			break;
		case 6:
			// Location activity.
			classe = LocationListActivity.class;
			break;
		case 7:
			// Commander activity.
			classe = CommanderListActivity.class;
			break;
		case 8:
			// Medical activity.
			classe = MedicalListActivity.class;
			break;
		case 9:
			// Responder activity.
			classe = ResponderListActivity.class;
			break;
		case 10:
			// Volunteer activity.
			classe = VolunteerListActivity.class;
			break;
		case 11:
			// Victim activity.
			classe = VictimListActivity.class;
			break;
		case 12:
			// Witness activity.
			classe = WitnessListActivity.class;
			break;
		case 13:
			// Contact activity.
			classe = ContactListActivity.class;
			break;
		case 14:
			// Plan activity.
			classe = PlanListActivity.class;
			break;
		case 15:
			// TextMessage activity.
			classe = TextMessageListActivity.class;
			break;
		case 16:
			// Team activity.
			classe = TeamListActivity.class;
			break;
		default:
			break;
		}

		if (classe != null) {
            // Launching activity selected.
            Intent i = new Intent(getApplicationContext(), classe);
            startActivity(i);

			// Update selected item and title, then close the drawer.
            mainListView.setItemChecked(position, true);
            mainListView.setSelection(position);
			//setTitle(navMenuTitles[position]);
		} else {
			// Error in creating fragment.
			Log.e("MainActivity", "Error in creating activity.");
		}
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_list_activity, menu);
		// Hiding menu New.
		menu.getItem(0).setVisible(false);
		// Hiding menu Save.
		menu.getItem(1).setVisible(false);
		return true;
	}

    @Override
    public void onBackPressed() {
    	// Clicking TWICE the back button to exit activity.
    	// You may also add condition in case of Fragment-based add.
    	// 		if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) 
        if (mRecentlyBackPressed) {
            mExitHandler.removeCallbacks(mExitRunnable);
            mExitHandler = null;
            super.onBackPressed();
        } else {
            mRecentlyBackPressed = true;
            Toast.makeText(this, "Press twice to EXIT.", Toast.LENGTH_SHORT).show();
            mExitHandler.postDelayed(mExitRunnable, delay);
        }
    }

}
